<template>
  <div class="grades-page">
    <div class="page-header">
      <h2 class="page-title">成绩管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        录入成绩
      </el-button>
    </div>

    <!-- 筛选器 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="selectedClass" placeholder="选择班级" clearable @change="handleFilter">
            <el-option
              v-for="cls in appStore.classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.name"
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="selectedCourse" placeholder="选择课程" clearable @change="handleFilter">
            <el-option
              v-for="course in appStore.courses"
              :key="course.id"
              :label="course.name"
              :value="course.name"
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="selectedSemester" placeholder="选择学期" clearable @change="handleFilter">
            <el-option label="2023-1" value="2023-1" />
            <el-option label="2023-2" value="2023-2" />
            <el-option label="2024-1" value="2024-1" />
            <el-option label="2024-2" value="2024-2" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-button type="primary" @click="exportGrades">
            <el-icon><Download /></el-icon>
            导出成绩
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 成绩表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="filteredGrades" stripe class="grades-table" max-height="600">
        <el-table-column prop="student_name" label="学生姓名" width="100" />
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="class_name" label="班级" width="150" />
        <el-table-column prop="course_name" label="课程" width="120" />
        <el-table-column prop="score" label="成绩" width="80">
          <template #default="{ row }">
            <el-tag :type="getScoreType(row.score)" size="large">
              {{ row.score }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" />
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.score >= 60 ? 'success' : 'danger'" size="small">
              {{ row.score >= 60 ? '及格' : '不及格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="exam_date" label="考试日期" width="120" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="editGrade(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteGrade(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 成绩统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <el-statistic
            title="总成绩条数"
            :value="filteredGrades.length"
            suffix="条"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <el-statistic
            title="平均分"
            :value="averageScore"
            :precision="1"
            suffix="分"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <el-statistic
            title="及格率"
            :value="passRate"
            :precision="1"
            suffix="%"
          />
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <el-statistic
            title="优秀率"
            :value="excellentRate"
            :precision="1"
            suffix="%"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      :title="isEditing ? '编辑成绩' : '录入成绩'"
      v-model="showAddDialog"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="gradeFormRef"
        :model="gradeForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="学生" prop="student_id">
          <el-select v-model="gradeForm.student_id" placeholder="请选择学生" filterable>
            <el-option
              v-for="student in mockStudents"
              :key="student.id"
              :label="`${student.name} (${student.student_id})`"
              :value="student.student_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="course_name">
          <el-select v-model="gradeForm.course_name" placeholder="请选择课程">
            <el-option
              v-for="course in appStore.courses"
              :key="course.id"
              :label="course.name"
              :value="course.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input-number
            v-model="gradeForm.score"
            :min="0"
            :max="100"
            :precision="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="gradeForm.semester" placeholder="请选择学期">
            <el-option label="2023-1" value="2023-1" />
            <el-option label="2023-2" value="2023-2" />
            <el-option label="2024-1" value="2024-1" />
            <el-option label="2024-2" value="2024-2" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试日期" prop="exam_date">
          <el-date-picker
            v-model="gradeForm.exam_date"
            type="date"
            placeholder="请选择考试日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEditing ? '更新' : '录入' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../stores/app'

const appStore = useAppStore()

const showAddDialog = ref(false)
const isEditing = ref(false)
const selectedClass = ref('')
const selectedCourse = ref('')
const selectedSemester = ref('')
const gradeFormRef = ref()

// 模拟学生数据
const mockStudents = ref([
  { id: 1, name: '张三', student_id: '2023001001', class_name: '计算机科学与技术1班' },
  { id: 2, name: '李四', student_id: '2023001002', class_name: '计算机科学与技术1班' },
  { id: 3, name: '王五', student_id: '2023001003', class_name: '计算机科学与技术2班' },
  { id: 4, name: '赵六', student_id: '2023001004', class_name: '软件工程1班' }
])

// 模拟成绩数据
const mockGrades = ref([
  {
    id: 1,
    student_name: '张三',
    student_id: '2023001001',
    class_name: '计算机科学与技术1班',
    course_name: '高等数学',
    score: 85,
    credit: 4,
    semester: '2023-1',
    exam_date: '2023-12-15'
  },
  {
    id: 2,
    student_name: '张三',
    student_id: '2023001001',
    class_name: '计算机科学与技术1班',
    course_name: '程序设计基础',
    score: 92,
    credit: 3,
    semester: '2023-1',
    exam_date: '2023-12-18'
  },
  {
    id: 3,
    student_name: '李四',
    student_id: '2023001002',
    class_name: '计算机科学与技术1班',
    course_name: '高等数学',
    score: 78,
    credit: 4,
    semester: '2023-1',
    exam_date: '2023-12-15'
  },
  {
    id: 4,
    student_name: '王五',
    student_id: '2023001003',
    class_name: '计算机科学与技术2班',
    course_name: '数据结构',
    score: 88,
    credit: 3,
    semester: '2023-2',
    exam_date: '2024-06-10'
  }
])

// 成绩表单数据
const gradeForm = reactive({
  id: null,
  student_id: '',
  course_name: '',
  score: 0,
  semester: '',
  exam_date: ''
})

// 表单验证规则
const formRules = {
  student_id: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  course_name: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入成绩', trigger: 'blur' }
  ],
  semester: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  exam_date: [
    { required: true, message: '请选择考试日期', trigger: 'change' }
  ]
}

// 计算属性
const filteredGrades = computed(() => {
  let grades = mockGrades.value

  if (selectedClass.value) {
    grades = grades.filter(grade => grade.class_name === selectedClass.value)
  }

  if (selectedCourse.value) {
    grades = grades.filter(grade => grade.course_name === selectedCourse.value)
  }

  if (selectedSemester.value) {
    grades = grades.filter(grade => grade.semester === selectedSemester.value)
  }

  return grades
})

const averageScore = computed(() => {
  if (filteredGrades.value.length === 0) return 0
  const total = filteredGrades.value.reduce((sum, grade) => sum + grade.score, 0)
  return total / filteredGrades.value.length
})

const passRate = computed(() => {
  if (filteredGrades.value.length === 0) return 0
  const passCount = filteredGrades.value.filter(grade => grade.score >= 60).length
  return (passCount / filteredGrades.value.length) * 100
})

const excellentRate = computed(() => {
  if (filteredGrades.value.length === 0) return 0
  const excellentCount = filteredGrades.value.filter(grade => grade.score >= 90).length
  return (excellentCount / filteredGrades.value.length) * 100
})

// 方法
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

const handleFilter = () => {
  // 过滤逻辑已在计算属性中处理
}

const exportGrades = () => {
  ElMessage.success('成绩导出功能开发中...')
}

const editGrade = (grade) => {
  isEditing.value = true
  showAddDialog.value = true
  Object.assign(gradeForm, grade)
}

const deleteGrade = async (grade) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除${grade.student_name}的${grade.course_name}成绩吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = mockGrades.value.findIndex(g => g.id === grade.id)
    if (index !== -1) {
      mockGrades.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    await gradeFormRef.value.validate()
    
    // 获取学生信息
    const student = mockStudents.value.find(s => s.student_id === gradeForm.student_id)
    if (!student) {
      ElMessage.error('学生信息不存在')
      return
    }

    // 获取课程信息
    const course = appStore.courses.find(c => c.name === gradeForm.course_name)
    if (!course) {
      ElMessage.error('课程信息不存在')
      return
    }

    if (isEditing.value) {
      // 更新成绩
      const index = mockGrades.value.findIndex(g => g.id === gradeForm.id)
      if (index !== -1) {
        Object.assign(mockGrades.value[index], {
          ...gradeForm,
          student_name: student.name,
          class_name: student.class_name,
          credit: course.credits
        })
      }
      ElMessage.success('更新成功')
    } else {
      // 添加成绩
      const newGrade = {
        ...gradeForm,
        id: Date.now(),
        student_name: student.name,
        class_name: student.class_name,
        credit: course.credits
      }
      mockGrades.value.push(newGrade)
      ElMessage.success('录入成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(isEditing.value ? '更新失败' : '录入失败')
    }
  }
}

const resetForm = () => {
  isEditing.value = false
  Object.assign(gradeForm, {
    id: null,
    student_id: '',
    course_name: '',
    score: 0,
    semester: '',
    exam_date: ''
  })
  if (gradeFormRef.value) {
    gradeFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      appStore.fetchClasses(),
      appStore.fetchCourses()
    ])
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.grades-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-weight: 500;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.grades-table {
  width: 100%;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  text-align: center;
}

.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-card .el-col {
    margin-bottom: 10px;
  }
  
  .grades-table {
    font-size: 12px;
  }
  
  .stats-row .el-col {
    margin-bottom: 10px;
  }
}
</style> 